package dao

import (
	"fmt"
	"time"

	"cron-go/internal/pkg/crontab/models"
	"cron-go/internal/pkg/database/mysql"

	"github.com/go-liam/util/response"
)

type WorkerDao struct {
}

func (e *WorkerDao) FindOneByName(name string) (*models.WorkerMysqlModel, error) {
	item := new(models.WorkerMysqlModel)
	sql := "select * from cron_worker where name =?  and is_delete =0 limit 1 "
	v := mysql.GetDB(mysql.DB_NAME).Raw(sql, name).Scan(item)
	return item, v.Error
}

func (e *WorkerDao) FindOneByID(id int64) (*models.WorkerMysqlModel, error) {
	item := new(models.WorkerMysqlModel)
	sql := "select * from cron_worker where id =?  and is_delete =0 limit 1 "
	v := mysql.GetDB(mysql.DB_NAME).Raw(sql, id).Scan(item)
	return item, v.Error
}

func (e *WorkerDao) Create(item *models.WorkerMysqlModel) (int64, error) {
	item.CreatedAt = time.Now().Unix()
	item.UpdatedAt = item.CreatedAt
	v := mysql.GetDB(mysql.DB_NAME).Create(item)
	return v.RowsAffected, v.Error
}

func (e *WorkerDao) FindMulti(p *response.Pagination, s *response.ListParameter) ([]*models.WorkerMysqlModel, error) {
	var result []*models.WorkerMysqlModel
	sqlLimit := fmt.Sprintf(" limit %d , %d  ", (p.Current-1)*p.PageSize, p.PageSize)
	sqlWhere := " is_delete = 0 " + s.WhereSt
	sql := "select * from cron_worker where " + sqlWhere + s.OrderSt + sqlLimit
	mysql.GetDB(mysql.DB_NAME).Model(&models.WorkerMysqlModel{}).Where(sqlWhere).Count(&p.Total)
	v := mysql.GetDB(mysql.DB_NAME).Raw(sql).Scan(&result)
	return result, v.Error
}

func (e *WorkerDao) Update(item *models.WorkerMysqlModel) (int64, error) {
	sql := "update `cron_worker` set `name` = ? where `id` = ?"
	v := mysql.GetDB(mysql.DB_NAME).Exec(sql, item.Name, item.ID)
	return v.RowsAffected, v.Error
}

func (e *WorkerDao) Delete(id int64) (int64, error) {
	date := time.Now().Unix()
	sql := "update `cron_worker` set `is_delete` = 1 , `updated_at` = ?  where `id` = ? ; "
	v := mysql.GetDB(mysql.DB_NAME).Exec(sql, date, id)
	return v.RowsAffected, v.Error
}

func (e *WorkerDao) Clear() (int64, error) {
	date := time.Now().Unix() - 60*60*24
	sql := fmt.Sprintf(" delete from `cron_worker` where `id` > 0 and `is_delete` = 1 and `updated_at` < %v ; ", date)
	println(sql)
	v := mysql.GetDB(mysql.DB_NAME).Exec(sql)
	return v.RowsAffected, v.Error
}
